package com.lianjia.analysis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.CompoundIndexDefinition;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.index.IndexDefinition;
import org.springframework.data.mongodb.core.index.IndexOperations;

import jakarta.annotation.PostConstruct;
import org.bson.Document;

/**
 * MongoDB配置类，用于创建索引
 */
@Configuration
public class MongoConfig {

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostConstruct
    public void initIndexes() {
        // 为HouseInfo集合创建索引
        IndexOperations indexOps = mongoTemplate.indexOps("house_info");
        
        // 城市名称索引 - 用于按城市查询
        indexOps.ensureIndex(new Index().on("cityName", Sort.Direction.ASC));
        
        // 区域索引 - 用于按区域查询
        indexOps.ensureIndex(new Index().on("district", Sort.Direction.ASC));
        
        // 价格索引 - 用于价格区间查询
        indexOps.ensureIndex(new Index().on("price.totalPrice", Sort.Direction.ASC));
        indexOps.ensureIndex(new Index().on("price.unitPrice", Sort.Direction.ASC));
        
        // 面积索引 - 用于面积区间查询
        indexOps.ensureIndex(new Index().on("details.areaValue", Sort.Direction.ASC));
        
        // 复合索引 - 城市+区域
        org.bson.Document compoundIndex = new org.bson.Document();
        compoundIndex.put("cityName", 1);
        compoundIndex.put("district", 1);
        indexOps.ensureIndex(new CompoundIndexDefinition(compoundIndex));
        
        // 复合索引 - 城市+价格
        compoundIndex = new org.bson.Document();
        compoundIndex.put("cityName", 1);
        compoundIndex.put("price.totalPrice", 1);
        indexOps.ensureIndex(new CompoundIndexDefinition(compoundIndex));
        
        // 复合索引 - 城市+面积
        compoundIndex = new org.bson.Document();
        compoundIndex.put("cityName", 1);
        compoundIndex.put("details.areaValue", 1);
        indexOps.ensureIndex(new CompoundIndexDefinition(compoundIndex));
        
        // 创建时间索引 - 用于最新房源查询
        indexOps.ensureIndex(new Index().on("createTime", Sort.Direction.DESC));
    }
} 